<!--
 * @Author: gy
 * @Date: 2019-12-24 15:13:01
 * @LastEditors  : gy
 * @LastEditTime : 2020-07-08 23:25:30
 -->
<!--  -->
<template>
  <div class="layout-content">
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <el-form-item label="登录名称" prop="login_name">
        <!-- <el-input v-model="form['login_name']" placeholder="请输入登录名称" /> -->
        <el-input v-model="form['login_name']" @blur="userNameCheck" placeholder="请输入登录名称" />
        <span class="errorText" v-show="form['checkParam']['uniqueNameValue']">该登录名称已经被注册</span>
      </el-form-item>
      <!--  -->
      <el-form-item label="部门名称" prop="dept_id">
        <div
          class="select-depart"
          @click="dialogVisibleDepart = true"
        >{{ treeObj.label ? treeObj.label: '选择部门' }}</div>
        <div v-if="dialogVisibleDepart">
          <el-dialog
            title="部门选择"
            :visible.sync="dialogVisibleDepart"
            width="30%"
            :destroy-on-close="true"
            :append-to-body="true"
            top="30vh"
            :modal-append-to-body="false"
            @close="dialogVisibleDepart = false"
          >
            <div class="search-content">
              <div class="search-box">
                <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
                <span class="search-btn" @click="searchTreeData">查询</span>
              </div>
              <div class="tree-box">
                <div class="tree-fold">
                  <span @click="foldTree">折叠</span>
                  <i>/</i>
                  <span @click="openTree">打开</span>
                </div>
                <el-tree
                  class="filter-tree"
                  :data="treeData"
                  :props="defaultProps"
                  :default-expand-all="expanded"
                  :default-checked-keys="checkedKeys"
                  :check-strictly="true"
                  show-checkbox
                  node-key="id"
                  @check="treeCheck"
                  node-click="nodeClick"
                  @check-change="handleMetaNodeClick"
                  :filter-node-method="filterNode"
                  ref="tree"
                ></el-tree>
              </div>
            </div>
            <!-- <el-cascader
              v-model="form['parent_id']"
              :options="menuList"
              :props="props"
              collapse-tags
              ref="menu"
              placeholder="请选择部门"
              :show-all-levels="false"
            clearable></el-cascader>-->
            <span slot="footer" class="dialog-footer">
              <el-button @click="selectDepartCancel">取 消</el-button>
              <el-button type="primary" @click="selectDepartConfirm">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-form-item>
      <el-form-item label="用户名称" prop="user_name">
        <el-input v-model="form['user_name']" placeholder="请输入用户名称" />
      </el-form-item>
      <el-form-item v-show="!moduleHidden" label="密码" prop="password">
        <el-input v-model="form['password']" placeholder="请输入密码" />
        <!-- <span class="errorText" v-show="form['checkParam']['uniquePasswordValue']">该密码没有通过验证</span> -->
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form['email']" @blur="emailCheck" placeholder="请输入邮箱号" />
        <span class="errorText" v-show="form['checkParam']['uniqueEmailValue']">该邮箱已经被注册</span>
      </el-form-item>
      <el-form-item label="手机">
        <el-input v-model="form['phonenumber']" @blur="phoneCheck" placeholder="请输入手机号码" />
        <span class="errorText" v-show="form['checkParam']['uniquePhoneValue']">该手机号已经被注册</span>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="form['sex']" placeholder="请选择性别">
          <el-option label="男" value="0" />
          <el-option label="女" value="1" />
          <el-option label="未知" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="form['status']"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="0"
          inactive-value="1"
        ></el-switch>
      </el-form-item>
      <el-form-item label="岗位" prop="postIds">
        <el-select v-model="form['postIds']" multiple placeholder="请选择岗位">
          <el-option
            v-for="item in postList"
            :key="item.pk_id"
            :label="item.post_name"
            :value="item.pk_id"
          ></el-option>
        </el-select>
        <!-- <el-input v-model="form.file9" placeholder="请输入岗位" /> -->
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <!-- <el-checkbox-group v-model="form['roleIdList']">
          <el-checkbox v-for="item in roleList" :key="item.role_code" :label="item.role_code">
          </el-checkbox>
        </el-checkbox-group>-->
        <el-select v-model="form['roleIds']" multiple placeholder="请选择角色">
          <el-option
            v-for="item in roleList"
            :key="item.pk_id"
            :label="item.role_name"
            :value="item.pk_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form['remark']" placeholder="备注信息" />
        <!-- <el-checkbox-group v-model="form['remark']">
          <el-checkbox v-for="(item, index) in userRemarkList" :key="index" :label="item">
          </el-checkbox>
        </el-checkbox-group>-->
      </el-form-item>
    </el-form>
    <!-- <div class="handle-btn">
      <el-button type="primary" @click="handleConfirm">确定</el-button>
      <el-button @click="handleCancel">关闭</el-button>
    </div>-->
  </div>
</template>

<script>
import {
  getUserDeptInfo,
  getGetDeptTreeData, // 部门树
  getUserPostList,
  getUserRoleList,
  checkLoginNameUnique, // 检查用户登录名称唯一性
  checkPassword, // 密码检测
  checkPhoneUnique, // 检查用户用户手机号唯一性
  checkEmailUnique // 检查用户邮箱唯一性
} from "@/api/api";
import SystemMixin from "@/mixins/SystemMixin";
export default {
  name: "AddUser",
  props: {
    titles: {
      type: String,
      default: () => ""
    }
  },
  mixins: [SystemMixin],
  data() {
    // let deptId = (rule, value, fn) => {
    //   let idList = this.$refs['tree'].getCheckedNodes();
    //   if(idList.length === 0) {
    //     fn(new Error('请选择部门'))
    //   } else {
    //     fn();
    //   }
    // };
    return {
      expanded: "",
      filterText: "",
      treeObj: {
        id: "",
        label: ""
      },
      defaultProps: {
        children: "children",
        label: "name"
      },
      checkedKeys: [], // 默认打开的(回显)
      props: {},
      menuList: [],
      dialogVisibleDepart: false,
      form: {
        login_name: "",
        dept_id: "",
        user_name: "",
        password: "",
        email: "",
        phonenumber: "",
        sex: "",
        status: "",
        // uniqueValue: 0, // 唯一性
        remark: "", // 备注
        // 唯一性检测
        checkParam: {
          uniqueNameValue: false,
          // uniquePasswordValue: false,
          uniqueEmailValue: false,
          uniquePhoneValue: false
        },
        postIds: [],
        roleIds: []
      },
      rules: {
        dept_id: [
          {
            required: true,
            message: "请输选择部门",
            trigger: 'change'
          }
        ],
        login_name: [
          {
            required: true,
            message: "请输入登录名称",
            trigger: "blur"
          }
        ],
        user_name: [
          {
            required: true,
            message: "请输用户昵称",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          }
        ],
        // sex
        sex: [
          {
            required: true,
            message: "请输选择性别",
            trigger: "change"
          }
        ],
        status: [
          {
            required: true,
            message: "请输选择状态",
            trigger: "change"
          }
        ],
        postIds: [
          {
            required: true,
            message: "请输选择部门",
            trigger: "change"
          }
        ],
        roleIds: [
          {
            required: true,
            message: "请输选择角色",
            trigger: "change"
          }
        ]
      },
      // checkRepeatParam: {
      //   url: '/system/api/User/checkLoginNameUnique',
      //   param: 'login_name',
      //   methods: 'get'
      // },
      userRemarkList: [
        "管理员",
        "计划员",
        "普通角色",
        "设计人员",
        "项目管理人员"
      ],
      // 部分
      moduleHidden: false,
      editCheckId: "",
      postList: [],
      roleList: []
    };
  },
  created() {
    // 部门树
    getGetDeptTreeData().then(res => {
      if (res.code === 0) {
        this.treeData = this.assembleTreeData(res.data, "id", "pId");
      }
      // let arr = [];
      // res.data.forEach(item => {
      //   if(item.pId === '0') {
      //     arr.push(item)
      //   }
      //   item.children = res.data.filter(items => items.pId === item.id)
      // })
      // this.treeData = this.handleTreeData(arr)
      // console.log(this.treeData, 'this.treeData')
    });
    // // 部门部门信息-按照用户id
    // getUserDeptInfo({ pid: this.uid }).then(res => {
    //   console.log(res, 'getUserDeptInfo')
    // })

    // 岗位信息
    getUserPostList({ pid: this.uid }).then(res => {
      if (res.code === 0) {
        this.postList = res.data;
      }
      console.log(res, "getUserPostList");
    });
    // 角色信息
    getUserRoleList({ pid: this.uid }).then(res => {
      if (res.code === 0) {
        this.roleList = res.data;
      }
      console.log(this.roleList, "getUserRoleList");
    });
  },
  mounted() {},
  watch: {
    // 标题监听
    titles: {
      handler(val) {
        if (val === "新增") {
          this.moduleHidden = false;
        } else {
          this.moduleHidden = true;
        }
      },
      immediate: true
    },
    // // 过滤字段
    // filterText(val) {
    //   this.$refs.tree.filter(val);
    // },
    // 部门弹窗监听
    dialogVisibleDepart: {
      handler(val) {
        if (!val) {
          this.filterText = "";
          this.editCheckId = "";
          // this.treeObj = {}
        }
      },
      immediate: true
    },
    // "form.dept_id": {
    //   handler(val) {
    //     this.checkedKeys[0] = val;
    //   },
    //   immediate: true
    // },
    "form.pk_id": {
      handler(val) {
        if(!val) return false
        getUserDeptInfo({ pid: val }).then(res => {
          if (res.code === 0) {
            this.checkedKeys[0] = res.data["dept_id"];
            this.treeObj["label"] = res.data["dept_name"];
            console.log(this.treeObj);
          }
        });
      },
      immediate: true
    }
  },
  methods: {
    // 过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    searchTreeData() {
      clearTimeout(this.timeOut)
      this.timeOut = setTimeout(() => {
        this.$refs.tree.filter(this.filterText);
      }, 500)
    },
    // 实现单选
    handleMetaNodeClick(item, node, self) {
      if (node === true) {
        this.editCheckId = item.id;
        this.$refs["tree"].setCheckedKeys([item.id]);
      } else {
        if (this.editCheckId === item.id) {
          this.$refs["tree"].setCheckedKeys([item.id]);
        }
      }
    },
    nodeClick(item, node, self) {
      this.editCheckId = item.id;
      this.$refs["tree"].setCheckedKeys([item.id]);
    },
    // 选择
    treeCheck(item, data) {
      this.treeObj = {
        id: item.id,
        label: item.name
      };
      this.form["dept_id"] = this.treeObj["id"];
    },
    // tree-展开
    openTree() {
      let treeList = this.data;
      this.$nextTick(() => {
        console.log(this.$refs.tree);
        // for (let i = 0; i < treeList.length; i++) {
        //   console.log(this.$refs['tree'].store.nodesMap[treeList[i].id])
        //   // this.$refs['tree'].store.nodesMap[treeList[i].id].expanded = false
        // }
      });
    },
    // tree-收缩
    foldTree() {
      let treeList = this.data;
      this.$nextTick(() => {
        console.log(this.$refs.tree);
        // console.log(this.$refs.tree.store._getAllNodes().length)
        // // for (let i = 0; i < treeList.length; i++) {
        // //   this.$refs['tree'].store.nodesMap[treeList[i].id].expanded = true
        // // }
      });
    },
    // 部门选择-确认
    selectDepartConfirm() {
      this.form["dept_id"] = this.treeObj["id"];
      this.dialogVisibleDepart = false;
    },
    // 部门选择-取消
    selectDepartCancel() {
      this.treeObj = {};
      this.dialogVisibleDepart = false;
    },
    // 用户名
    async userNameCheck() {
      if (this.form["login_name"] === "") {
        this.form["checkParam"]["uniqueNameValue"] = false;
      } else {
        this.form["checkParam"]["uniqueNameValue"] = await this.checkUnique(
          "/system/api/User/CheckLoginNameUnique",
          {
            login_name: this.form["login_name"]
          }
        );
      }
    },
    // 需要获取登录用户 id
    // async passwordCheck() {
    //   // if(this.form['password'] === '') {
    //   //   this.form['checkParam']['uniquePasswordValue'] = false
    //   // } else {
    //   //   this.form['checkParam']['uniquePasswordValue'] = await this.checkUnique(
    //   //     '/system/api/User/CheckPassword',
    //   //     { 'password': this.form['password'], 'userId': this.uid ? this.uid : ''});
    //   // }
    //   // if(val === '') return false
    //   // this.$forceUpdate()
    //   // clearTimeout(this.setTime);
    //   // this.setTime = setTimeout(() => {
    //   //   checkPassword({ 'userId': this.uid ? this.uid : '', 'password': this.form['password']}).then(res => {
    //   //     if(res.code === 0 || res.code === 500){
    //   //       this.form['checkParam']['uniquePasswordValue'] = res['data'];
    //   //     }
    //   //   })
    //   // }, 500)
    // },
    // 邮箱
    async emailCheck() {
      if (this.form["email"] === "") {
        this.form["checkParam"]["uniqueEmailValue"] = false;
      } else {
        this.form["checkParam"]["uniqueEmailValue"] = await this.checkUnique(
          "/system/api/User/CheckEmailUnique",
          {
            email: this.form["email"]
          }
        );
      }
    },
    // 手机号
    async phoneCheck() {
      if (this.form["phonenumber"] === "") {
        this.form["checkParam"]["uniquePhoneValue"] = false;
      } else {
        this.form["checkParam"]["uniquePhoneValue"] = await this.checkUnique(
          "/system/api/User/CheckPhoneUnique",
          {
            phonenumber: this.form["phonenumber"]
          }
        );
      }
    }
    // handleConfirm() {
    //   this.$emit('handleConfirm', this.checkParam)
    // },
    // handleCancel() {
    //   this.$emit('handleCancel')
    // }
  }
};
</script>
<style lang="scss" scoped>
.select-depart {
  width: 107px;
  line-height: 34px;
  background: linear-gradient(
    0deg,
    rgba(70, 127, 255, 1),
    rgba(126, 166, 253, 1)
  );
  box-shadow: 0px 5px 7px 0px rgba(213, 215, 218, 0.9);
  border-radius: 4px;
  color: rgba(255, 255, 255, 1);
  text-align: center;
  cursor: pointer;
}
// // tree
// .search-content {
//   position: relative;
//   .search-box {
//     margin-bottom: 10px;
//     display: flex;
//     align-items: center;
//     justify-content: space-between;
//     .el-input {
//       // width: 80%;
//       flex: 1;
//     }
//     .search-btn {
//       display: block;
//       cursor: pointer;
//       line-height: 36px;
//       background:linear-gradient(0deg, #4680ff, #7fa7fd);
//       color: #fff;
//       padding: 0 5px;
//       margin-left: 10px;
//       border-radius: 3px;
//     }
//   }
//   .tree-box {
//     position: relative;
//     .tree-fold {
//       display: flex;
//       position: absolute;
//       right: 0px;
//       top: 0px;
//       z-index: 9;
//       line-height: 26px;
//       align-items: center;
//       span {
//         cursor: pointer;
//       }
//       i {
//         margin: 0 5px;
//       }
//     }
//   }
// }
</style>
